package com.fjec.activity.rabbitmq.consumer;

import com.fjec.activity.service.IBizActivitySeckillService;
import com.fjec.common.protocol.FjecFruitsProto;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
public class SecKillConsumer {

    @Resource
    private IBizActivitySeckillService bizActivitySeckillService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "${fjec.activity.seckill.queue.name}",
                            durable = "${fjec.activity.seckill.queue.durable}"
                    ),
                    exchange = @Exchange(
                            value = "${fjec.activity.seckill.exchange.name}",
                            durable = "${fjec.activity.seckill.exchange.durable}",
                            type = "${fjec.activity.seckill.exchange.type}",
                            ignoreDeclarationExceptions = "${fjec.activity.seckill.exchange.ignoreDeclarationExceptions}"
                    ),
                    key = "${fjec.activity.seckill.router.key}"
            )
    )
    @RabbitHandler
    public void onSecKill(Message message, Channel channel, @Headers Map<String, Object> headers) throws Exception {
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            FjecFruitsProto.FjecFruitsMsg msg = FjecFruitsProto.FjecFruitsMsg.parseFrom(message.getBody());
            if (msg.hasSecKill()) {
                FjecFruitsProto.SecKill secKill = msg.getSecKill();
                if (secKill.getUserId() != 0 && secKill.getSecKillId() != 0) {
                    bizActivitySeckillService.doKill(secKill.getUserId(), secKill.getSecKillId(), secKill.getShopName());
                    channel.basicAck(deliveryTag, true);
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            channel.basicReject(deliveryTag, false);
        }
    }
}
